require 'libvidere'
require 'thread'

unless $probetype
  puts "No probetype given with -p" 
  exit 1
end

module Videre
  module Command
    def handle_message(msg)
      # A simple one, very usefull for debuggin
      if msg.body =~ /^ping/
        self.deliver(msg.from, "pong")
      elsif msg.body =~ /^check/
        puts "Implement me!"
      elsif msg.body =~ /^add_check/
        if check=self.strip_command("add_check", msg)
          id, interval, check = check.split(/\s/, 3)
          check=self.object_from_command("", check)
          $scheduled_checks[id] = ScheduledCheck.new(id, check, interval)
        end
      else
        puts "Cannot handle message " + msg.body if $debug
      end
    end
  end
end

begin
eval "
module Videre
  module Probes
  class Probe
    include Videre::Probe
    include Videre::Probes::#{$probetype.capitalize}::Request
    include Videre::Probes::#{$probetype.capitalize}::Result
    include Videre::Probes::#{$probetype.capitalize}::Command
  end
end
end
"
rescue NoMethodError, NameError
  puts "No valid probetype given with -p"
  exit 1
rescue SyntaxError
  puts "The probe $probetype doesn't contain valid ruby code, please correct"
  exit 1
end

class Videre::Client
  def run_queue
    if $checkqueue.size > 0
      running=Array.new
      $checkqueue.size.times do
        running << Thread.new do
          item=$checkqueue.pop
          item.last=Time.now # set the last run before actually doing it
          self.send_to_prog( 'processor', self.jid, "result " + item.check.run_check)
        end
      end
    end
    if $checkqueue.size > 5 
       $self.log.notice "Getting too busy"
    end
    
    $scheduled_checks.each_value do | schedule |
      if schedule.should_run?
        $checkqueue << schedule
        schedule.last = Time.now
      end
    end
  end
end

class ScheduledCheck
  attr_accessor :id, :check, :interval, :last
  
  def initialize(id, check, interval=60)
    @id=id.to_i
    @check=check
    @interval=interval.to_i
    @last=Time.now
    
    def should_run?
      checktime = Time.now - @interval
      true if @last <= checktime
    end
  end
end

client=Videre::Client.new("check_#{$probetype}")
client.become_daemon
$scheduled_checks=Hash.new
$checkqueue=Queue.new
client.work
